package trees;

public class GenerateMatrix {
    public int[][] generateMatrix(int n) {
        int left = 0;
        int right = n - 1;
        int top = 0;
        int bottom = n - 1;
        int index = 1;

        int[][] result = new int[n][n];
        while (index <= n * n) {
            // 从左到右
            for (int i = left; i <= right; i++) {
                result[top][i] = index;
                index++;
            }
            top++;

            // 从上到下
            for (int i = top; i <= bottom; i++) {
                result[i][right] = index;
                index++;
            }
            right--;

            // 从右到左
            for (int i = right; i >= left; i--) {
                result[bottom][i] = index;
                index++;
            }
            bottom--;

            // 从下到上
            for (int i = bottom; i >= top; i--) {
                result[i][left] = index;
                index++;
            }
            left++;
        }

        return result;
    }

    public static void main(String[] args) {
        GenerateMatrix matrix = new GenerateMatrix();
        int[][] result = matrix.generateMatrix(4);

        for (int[] ints : result) {
            for (int j = 0; j < result[0].length; j++) {
                System.out.print(ints[j] + " ");
            }
            System.out.println();
        }
    }
}
